﻿using S7.Net;
using S7Client.Base;
using S7Client.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static S7Client.S7V2.Responses;
using System.Xml.XPath;
using System.Windows.Media;

namespace S7Client.ViewModel
{
    public class MainViewModel : NotifyBase
    {

        public ConfigModel ConfigModel { get; set; } = new ConfigModel();
        public List<string> PlcTypeList { get; set; } = new List<string>();
        public List<string> DataTypeList { get; set; } = new List<string>();
        public List<string> VarTypeList { get; set; } = new List<string>();


        private string _connLog = "日志\r\n";

        public string ConnLog
        {
            get { return _connLog; }
            set { _connLog = value; this.NotifyChanged(); }
        }

        private string _log;

        public string WToRLog
        {
            get { return _log; }
            set { _log = value; this.NotifyChanged(); }
        }

        private string _deviceStatus="1";

        public string DeviceStatus
        {
            get { return _deviceStatus; }
            set { _deviceStatus = value; this.NotifyChanged(); }
        }


        public MainViewModel()
        {
            ConfigModel.Ip = "192.168.0.1";
            ConfigModel.PlcType = "S71500";
            ConfigModel.Rack = 0;
            ConfigModel.Slot = 1;
            ConfigModel.DataType = "DataBlock";
            ConfigModel.DBArea = "10"; 
            ConfigModel.WriteDataType = "Int";
            ConfigModel.VarCount = 1;
            ConfigModel.BitAdr = "0";


            string[] plcTypeArr = Enum.GetNames(typeof(CpuType));
            foreach (var item in plcTypeArr)
                PlcTypeList.Add(item);

            string[] dataTypeArr = Enum.GetNames(typeof(DataType));
            foreach (var item in dataTypeArr)
                DataTypeList.Add(item);

            string[] VarTypeArr = Enum.GetNames(typeof(VarType));
            foreach (var item in VarTypeArr)
                VarTypeList.Add(item);

        }

        private CommandBase _plcComm;

        public CommandBase PlcCommand
        {
            get
            {
                if (_plcComm == null)
                {
                    _plcComm = new CommandBase();
                    _plcComm.DoExecute = new Action<object>((obj) =>
                    {
                        connPlc();
                    });
                }
                return _plcComm;
            }
            set { _plcComm = value; }
        }

        private CommandBase _plcClose;

        public CommandBase PlcClose
        {
            get
            {
                if (_plcClose == null)
                {
                    _plcClose = new CommandBase();
                    _plcClose.DoExecute = new Action<object>((obj) =>
                    {
                        closePlc();
                    });
                }
                return _plcClose;
            }
            set { _plcClose = value; }
        }

        #region PLC 连接与断开
        private async void connPlc()
        {
            try
            {
                // 使用异步方法，防止WinForm界面卡顿（假死）
                await PlcController.MyPlc.Connect((CpuType)Enum.Parse(typeof(CpuType), ConfigModel.PlcType),
                                   ConfigModel.Ip,
                                   Convert.ToInt16(ConfigModel.Rack),
                                   Convert.ToInt16(ConfigModel.Slot));
                if (PlcController.MyPlc.IsConnected)
                {
                    ConnLog += $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}  连接成功！\r\n";
                }
            }
            catch (Exception ex)
            {
                // 处理读取错误
                ConnLog += $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}  {ex.Message}\r\n";
            }
        }

        private void closePlc()
        {
            try
            {
                PlcController.MyPlc.Disconnect();
                if (PlcController.MyPlc.IsConnected == false)
                {
                    ConnLog += $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}  断开成功！\r\n";
                }
            }
            catch (Exception ex)
            {
                // 处理读取错误
                ConnLog += $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}  {ex.Message}\r\n";
            }
        }
        #endregion



        private CommandBase _readConn;

        public CommandBase ReadCommand
        {
            get
            {
                if (_readConn == null)
                {
                    _readConn = new CommandBase();
                    _readConn.DoExecute = new Action<object>(obj =>
                    {
                        ReadData();
                    });
                }
                return _readConn;
            }
            set { _readConn = value; }
        }

        private CommandBase _writeComm;

        public CommandBase WriteCommand
        {
            get
            {
                if (_writeComm == null)
                {
                    _writeComm = new CommandBase();
                    _writeComm.DoExecute = new Action<object>((obj) =>
                    {
                        WriteData();
                    });
                }
                return _writeComm;
            }
            set { _writeComm = value; }
        }

        #region PLC 读写操作
        private void ReadData()
        {
            ReadResponce responce = PlcController.MyPlc.ReadVariable(
         (DataType)Enum.Parse(typeof(DataType), ConfigModel.DataType),
         Convert.ToInt16(ConfigModel.DBArea),
         Convert.ToInt16(ConfigModel.ByteAdr),
         (VarType)Enum.Parse(typeof(VarType), ConfigModel.WriteDataType),
         Convert.ToInt16(ConfigModel.VarCount),
         Convert.ToByte(ConfigModel.BitAdr)
        );
            if (responce == null)
            {
                WToRLog += $"{DateTime.Now.ToString("HH:mm:ss")}  读取失败！\r\n";
            }
            else if (responce.IsSuccess == false)
            {
                WToRLog += $"{DateTime.Now.ToString("HH:mm:ss")}  读取失败！{responce.ReaponceMsg}\r\n";
            }
            else
            {
                WToRLog += $"{DateTime.Now.ToString("HH:mm:ss")}  {responce.Data}\r\n";
            }
        }

        private void WriteData()
        {
            WriteResponce responce = PlcController.MyPlc.WriteVariable(
         (DataType)Enum.Parse(typeof(DataType), ConfigModel.DataType),
         Convert.ToInt16(ConfigModel.DBArea),
         Convert.ToInt16(ConfigModel.ByteAdr),
         (VarType)Enum.Parse(typeof(VarType), ConfigModel.WriteDataType),
         ConfigModel.Value,
         Convert.ToByte(ConfigModel.BitAdr)
         );
            if (responce == null)
            {
                WToRLog += $"{DateTime.Now.ToString("HH:mm:ss")}  写入失败！\r\n";
            }
            else if (responce.IsSuccess == false)
            {
                WToRLog += $"{DateTime.Now.ToString("HH:mm:ss")}  写入失败！{responce.ReaponceMsg}\r\n";
            }
            else
            {
                WToRLog += $"{DateTime.Now.ToString("HH:mm:ss")}  写入成功！\r\n";
            }
        }
        #endregion


        #region 测试设备 读写 及 启动

        //Motor motor;
        //private void btnCreateMotor_Click(object sender, EventArgs e)
        //{
        //    motor = new Motor("电机001", 2);
        //}
        //private void btnReadMotor_Click(object sender, EventArgs e)
        //{
        //    if (motor != null)
        //    {
        //        ReadResponce responce = motor.Read();

        //        if (responce == null)
        //        {
        //            txtDeviceLog.AppendText($"{DateTime.Now.ToString("HH:mm:ss")}  {motor.Name}读取失败！\r\n");
        //        }
        //        else if (responce.IsSuccess == false)
        //        {
        //            txtDeviceLog.AppendText($"{DateTime.Now.ToString("HH:mm:ss")}  {motor.Name}读取失败！{responce.ReaponceMsg}\r\n");
        //        }
        //        else
        //        {
        //            if (motor.CurrentStatus == 0)
        //            {
        //                ledMotorState.StatusColor = Color.Gray;
        //            }
        //            else if (motor.CurrentStatus == 1)
        //            {
        //                ledMotorState.StatusColor = Color.LimeGreen;
        //            }
        //            else
        //            {
        //                ledMotorState.StatusColor = Color.Red;
        //            }
        //        }
        //    }
        //    else
        //    {
        //        txtDeviceLog.AppendText($"{DateTime.Now.ToString("HH:mm:ss")}  电机未创建！\r\n");
        //    }
        //}

        //MobileDevice mobileDevice;
        //private void btnCreateMobile_Click(object sender, EventArgs e)
        //{
        //    mobileDevice = new MobileDevice("一维移动设备001", 2);
        //}

        //private void btnReadMobile_Click(object sender, EventArgs e)
        //{
        //    if (mobileDevice != null)
        //    {
        //        ReadResponce responce = mobileDevice.Read();

        //        if (responce == null)
        //        {
        //            txtDeviceLog.AppendText($"{DateTime.Now.ToString("HH:mm:ss")}  {mobileDevice.Name}读取失败！\r\n");
        //        }
        //        else if (responce.IsSuccess == false)
        //        {
        //            txtDeviceLog.AppendText($"{DateTime.Now.ToString("HH:mm:ss")}  {mobileDevice.Name}读取失败！{responce.ReaponceMsg}\r\n");
        //        }
        //        else
        //        {
        //            if (mobileDevice.CurrentStatus == 0)
        //            {
        //                ledMobileDeviceState.StatusColor = Color.Gray;
        //            }
        //            else if (mobileDevice.CurrentStatus == 1)
        //            {
        //                ledMobileDeviceState.StatusColor = Color.LimeGreen;
        //            }
        //            else
        //            {
        //                ledMobileDeviceState.StatusColor = Color.Red;
        //            }
        //        }
        //    }
        //    else
        //    {
        //        txtDeviceLog.AppendText($"{DateTime.Now.ToString("HH:mm:ss")}  移动设备未创建！\r\n");
        //    }
        //}

        //bool bAutoReadMotor = false;
        //bool bAutoReadMobile = false;

        //private void timerReadWrite_Tick(object sender, EventArgs e)
        //{
        //    DateTime now = DateTime.Now;
        //    int data = now.Second % 3;
        //    if (bAutoReadMotor && motor != null)
        //    {
        //        btnReadMotor_Click(null, null);
        //        motor.Write((short)data);
        //    }
        //    if (bAutoReadMobile)
        //    {
        //        btnReadMobile_Click(null, null);
        //        data = 3 - data;
        //        mobileDevice.Write((short)data);
        //    }
        //}

        //private void btnAutoReadMotor_Click(object sender, EventArgs e)
        //{
        //    bAutoReadMotor = !bAutoReadMotor;
        //}

        //private void btnAutoReadMobile_Click(object sender, EventArgs e)
        //{
        //    bAutoReadMobile = !bAutoReadMobile;
        //}

        // 这两个变量用于分别控制自动读写的开关。只有开启的时候，才会自动进行读写。
        bool bAutoReadMotor = false;
        bool bAutoReadMobile = false;

        // 方法的调用
        //btnReadMotor_Click(null, null);
        //btnReadMobile_Click(null, null);;

        #endregion
    }
}
